package com.skyworth.web.common.form;

import lombok.Data;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.ui.Model;

import java.util.HashMap;


@Data
public class Paginator {

    private static final int PAGE_SIZE = 10;

    public int rows;
    public int page;
    public String sord;
    public String sidx;

    public String getSidx() {
        return sidx;
    }

    public void setSidx(String sidx) {
        this.sidx = sidx;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public String getSord() {
        return sord;
    }

    public void setSord(String sord) {
        this.sord = sord;
    }

    public Pageable pageRequest() {
        Sort.Direction direction = Sort.Direction.DESC;
        if (null != sord && sord.equals("asc")) {
            direction = Sort.Direction.ASC;
        }
        String _sidx = sidx;
        if (null == _sidx || _sidx.length() == 0) {
            direction = Sort.Direction.DESC;
            _sidx = "id";
        }
        Sort sort = new Sort(direction, _sidx);
        int pageSize = PAGE_SIZE;
        if (rows > 0) {
            pageSize = rows;
        }
        int _page = this.page;
        if (_page > 0) {
            _page = _page - 1;
        }
        PageRequest request = new PageRequest(_page, pageSize, sort);
        return request;
    }

    public java.util.Map<String, Object> jqGridMap(Page page) {
        java.util.Map<String, Object> map = new HashMap<>();

        int current = page.getNumber() + 1;
        int begin = Math.max(1, current - 5);
        int end = Math.min(begin + 10, page.getTotalPages());

        map.put("rows", page.getContent());
        map.put("page", current);
        map.put("total", end);
        map.put("records", page.getTotalElements());

        return map;
    }


    public void feedToModel(Page page, Model model) {
        int current = page.getNumber() + 1;
        int begin = Math.max(1, current - 5);
        int end = Math.min(begin + 10, page.getTotalPages());

        model.addAttribute("rows", page.getContent());
        model.addAttribute("page", current);
        model.addAttribute("total", end);
        model.addAttribute("perpage", this.PAGE_SIZE);
        model.addAttribute("records",page.getTotalElements());
        model.addAttribute("rowSize", page.getContent().size());

    }
}
